<template>
  <div>
    <!-- 查询区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-card>
        <el-input
          v-model="a_repairStatus.id"
          placeholder="请输入设备ID查询"
          prefix-icon="Search"
          style="width: 200px; margin-right: 10px"
        />
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table
        :data="a_repairStatus.tableData"
        border
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55" />

        <!-- 序号列 -->
        <el-table-column label="编号" type="index" width="60" />

        <!-- 设备ID -->
        <el-table-column label="设备ID" prop="seid" />

        <!-- 备注 -->
        <el-table-column label="备注" prop="note" />

        <!-- 创建时间 -->
        <el-table-column label="创建时间" prop="createTime" />

        <!-- 更新时间 -->
        <el-table-column label="更新时间" prop="updateTime" />

        <!-- 操作列 -->
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <div>
            <el-button
              type="primary"
              :icon="Edit"
              size="small"
              @click="handleEdit(scope.row)"
            >编 辑</el-button></div>
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="handleDelete(scope.row)"
            >删 除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
          @size-change="load"
          @current-change="load"
          v-model:current-page="a_repairStatus.pageNumber"
          v-model:page-size="a_repairStatus.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="a_repairStatus.total"
          background
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="a_repairStatus.form.seid ? '编辑维修状态' : '新增维修状态'"
      v-model="a_repairStatus.formVisible"
      width="500"
    >
      <el-form :model="a_repairStatus.form" style="padding-right: 50px; padding-top: 20px;">
        <el-form-item label="设备ID" label-width="80px">
          <el-input v-model="a_repairStatus.form.seid" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="备注" label-width="80px">
          <el-input v-model="a_repairStatus.form.note" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="a_repairStatus.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const a_repairStatus = reactive({
  id: '',
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  tableData: [],
  formVisible: false,
  form: {},
  selectedRows: [] // 存储用户选择的行数据
})

// 加载数据
const load = () => {
  request.get('/v1/admin/selectPage', {
    params: {
      tableName: 'repair_status',
      id: a_repairStatus.id,
      pageNum: a_repairStatus.pageNumber,
      pageSize: a_repairStatus.pageSize
    }
  }).then(res => {
    console.log('响应数据:', res)
    if (res.state === 2001) {
      a_repairStatus.tableData = res.data.list || []
      a_repairStatus.total = res.data.total || 0
    } else {
      a_repairStatus.tableData = []
      a_repairStatus.total = 0
    }
  }).catch(error => {
    console.error('请求失败:', error)
    a_repairStatus.tableData = []
    a_repairStatus.total = 0
  })
}

// 重置查询条件
const reset = () => {
  a_repairStatus.id = ''
  load()
}

// 处理新增
const handleAdd = () => {
  a_repairStatus.form = {
    seid: '',
    note: ''
  }
  a_repairStatus.formVisible = true
}

// 处理编辑
const handleEdit = (row) => {
  a_repairStatus.form = { ...row }
  a_repairStatus.formVisible = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该维修状态吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/delete', {
      data: {
        tableName: 'repair_status',
        id: row.seid // 使用 seid 作为删除依据
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '删除成功', type: 'success' })
        load() // 重新加载数据
      } else {
        ElMessage({ message: '删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (a_repairStatus.selectedRows.length === 0) {
    ElMessage({ message: '请选择要删除的维修记录', type: 'warning' })
    return
  }

  const ids = a_repairStatus.selectedRows.map(row => row.seid)

  ElMessageBox.confirm('确定要删除这些维修记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/batchDelete', {
      data: {
        tableName: 'repair_status',
        ids: ids
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '批量删除成功', type: 'success' })
        load()
      } else {
        ElMessage({ message: '批量删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理表格多选变化
const handleSelectionChange = (rows) => {
  a_repairStatus.selectedRows = rows
}

// 保存新增或编辑
const save = () => {
  const seid = a_repairStatus.form.seid

  request.get('/v1/admin/checkEquipmentExist', {
    params: { seid }
  }).then(res => {
    if (res.state === 2001 && res.data.exists) {
      request.get('/v1/admin/checkRepairStatusExist', {
        params: { seid }
      }).then(res2 => {
        const isExisting = res2.data.exists
        const method = isExisting ? 'put' : 'post'
        const url = isExisting ? '/v1/admin/update' : '/v1/admin/add'

        const saveData = {
          seid: a_repairStatus.form.seid,
          note: a_repairStatus.form.note
        }

        request[method](url, {
          tableName: 'repair_status',
          data: saveData
        }).then(saveRes => {
          if (saveRes.state === 2001) {
            ElMessage({ message: isExisting ? '编辑成功' : '新增成功', type: 'success' })
            a_repairStatus.formVisible = false
            load()
          } else {
            ElMessage({ message: isExisting ? '编辑失败' : '新增失败', type: 'error' })
          }
        }).catch(error => {
          console.error('保存失败:', error)
          ElMessage({ message: '保存失败，请检查网络或服务器', type: 'error' })
        })
      }).catch(() => {
        ElMessage({ message: '设备无维修记录，准备新增', type: 'info' })

        const addData = {
          seid: a_repairStatus.form.seid,
          note: a_repairStatus.form.note
        }

        request.post('/v1/admin/add', {
          tableName: 'repair_status',
          data: addData
        }).then(res => {
          if (res.state === 2001) {
            ElMessage({ message: '新增成功', type: 'success' })
            a_repairStatus.formVisible = false
            load()
          } else {
            ElMessage({ message: '新增失败', type: 'error' })
          }
        }).catch(error => {
          console.error('请求失败:', error)
          ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
        })
      })
    } else {
      ElMessage({ message: '设备ID不存在，请先添加对应设备', type: 'error' })
    }
  }).catch(error => {
    console.error('请求失败:', error)
    ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
  })
}


// 初始化加载数据
load()
request.put('/v1/admin/update', {
  tableName: 'repair_status',
  data: {
    seid: a_repairStatus.form.seid,
    note: a_repairStatus.form.note
    // 不需要 createTime 字段
  }
})

// 路由参数处理
const route = useRoute()
onMounted(() => {
  const seid = route.params.seid
  if (seid) {
    a_repairStatus.id = seid
    load()
  }
})
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
</style>
